from typing import List, Optional

try:
    from .AIAssistant import AIAssistant  # type: ignore
    from .DataAnalysisAssistant import DataAnalysisAssistant  # type: ignore
    from .ImageGenerationAssistant import ImageGenerationAssistant  # type: ignore
    from .TextGenerationAssistant import TextGenerationAssistant  # type: ignore
    from .TranslationAssistant import TranslationAssistant  # type: ignore
    from .VoiceAssistant import VoiceAssistant  # type: ignore
except Exception:
    import os
    import sys
    sys.path.append(os.path.dirname(__file__))
    from AIAssistant import AIAssistant  # type: ignore
    from DataAnalysisAssistant import DataAnalysisAssistant  # type: ignore
    from ImageGenerationAssistant import ImageGenerationAssistant  # type: ignore
    from TextGenerationAssistant import TextGenerationAssistant  # type: ignore
    from TranslationAssistant import TranslationAssistant  # type: ignore
    from VoiceAssistant import VoiceAssistant  # type: ignore


class AInterface:
    def __init__(self) -> None:
        self.ais: List[Optional[AIAssistant]] = []

    def menu(self) -> None:
        print("欢迎使用 AI助手管理器 v1.0")
        while True:
            print("==========🤖AI助手管理器==========")
            print("1. 查看所有AI助手列表")
            print("2. 根据ID查询助手详情")
            print("3. 添加新的AI助手")
            print("4. 根据ID修改助手信息")
            print("5. 删除AI助手（按ID）")
            print("6. 启动AI助手服务")
            print("7. 停止AI助手服务")
            print("8. 为AI助手分配任务")
            print("9. 显示系统统计信息")
            print("0. 退出系统")
            print("================================")
            print("请选择操作:")
            try:
                choose = int(input())
            except Exception:
                print("输入类型错误，请重新输入整数类型")
                continue

            if choose == 1:
                self.showAI()
            elif choose == 2:
                self.inquiryAI()
            elif choose == 3:
                self.addAI()
            elif choose == 4:
                self.reviseAI()
            elif choose == 5:
                self.removeAI()
            elif choose == 6:
                self.startAI()
            elif choose == 7:
                self.stopAI()
            elif choose == 8:
                self.taskAI()
            elif choose == 9:
                self.statisticsAI()
            elif choose == 0:
                raise SystemExit(0)
            else:
                print("请输入对应的选择项数字")

    def showAI(self) -> None:
        result = False
        for ai in self.ais:
            if ai is not None:
                result = True
                status = "🔴离线" if ai.getState() == 0 else "🟢在线"
                print(
                    f"ID：{ai.getId()}，名称：{ai.getName()}，类型：{ai.getType()}，版本：{ai.getVer()}，状态:{status}, 能力评分:{ai.getScore()}[{ai.getType()}]"
                )
        if not result:
            print("管理器中没有AI助手，请添加AI助手")

    def inquiryAI(self) -> None:
        print("请输入需要查询的AI助手ID：")
        try:
            num_obj = int(input())
        except Exception:
            print("输入类型错误，请重新输入整数类型")
            return
        for ai in self.ais:
            if ai is not None and num_obj == ai.getId():
                status = "🔴离线" if ai.getState() == 0 else "🟢在线"
                print(
                    f"✅ 查询结果:ID：{ai.getId()}，名称：{ai.getName()}，类型：{ai.getType()}，版本：{ai.getVer()}，状态:{status}, 能力评分:{ai.getScore()}"
                )
                return
        print("未找到该AI助手，请确认ID是否错误")

    def addAI(self) -> None:
        print("添加新AI助手")
        ai_assistant = AIAssistant()
        print("请输入ID:")
        try:
            id_value = int(input())
        except Exception:
            print("输入类型错误，请重新输入整数类型")
            print("❌添加失败")
            return
        if id_value < 0:
            print("请输入正整数的ID")
            print("❌添加失败")
            return
        for ai in self.ais:
            if ai is not None and id_value == ai.getId():
                print("ID重复请重新输入")
                print("❌添加失败")
                return
        ai_assistant.setId(id_value)

        print("请输入名称:：")
        name_value = input().strip()
        ai_assistant.setName(name_value)

        if ai_assistant.containsChineseIgnoreCase(ai_assistant.getName(), ai_assistant.darry):
            ai_assistant.setType("数据分析助手")
        if ai_assistant.containsChineseIgnoreCase(ai_assistant.getName(), ai_assistant.iarry):
            ai_assistant.setType("图片生成助手")
        if ai_assistant.containsChineseIgnoreCase(ai_assistant.getName(), ai_assistant.garry):
            ai_assistant.setType("文本生成助手")
        if ai_assistant.containsChineseIgnoreCase(ai_assistant.getName(), ai_assistant.sarry):
            ai_assistant.setType("翻译助手")
        if ai_assistant.containsChineseIgnoreCase(ai_assistant.getName(), ai_assistant.varry):
            ai_assistant.setType("语音助手")
        if ai_assistant.getType() is None:
            ai_assistant.setType("文本生成助手")

        print("请输入版本号:")
        ver_value = input().strip()
        ai_assistant.setVer(ver_value)

        print("是否在线？(1-是, 0-否):")
        try:
            state_value = int(input())
        except Exception:
            print("输入类型错误，请重新输入整数类型")
            print("❌添加失败")
            return
        if state_value not in (0, 1):
            print("请输入正确的数字(1-是, 0-否)")
            print("❌添加失败")
            return
        ai_assistant.setState(state_value)

        print("请输入能力评分(0-100):")
        try:
            score_value = float(input())
        except Exception:
            print("输入类型错误，请重新输入整数类型")
            print("❌添加失败")
            return
        if score_value < 0 or score_value > 100:
            print("请输入正确的数字(0-100)")
            print("❌添加失败")
            return
        ai_assistant.setScore(score_value)

        # 放入列表（最大 20）
        if len(self.ais) < 20:
            self.ais.append(ai_assistant)
            print(f"✅添加助手【{ai_assistant.getName()}】成功")
        else:
            # 找空位替换为非 None 才能完全对齐 Java 的固定数组行为
            for i in range(len(self.ais)):
                if self.ais[i] is None:
                    self.ais[i] = ai_assistant
                    print(f"✅添加助手【{ai_assistant.getName()}】成功")
                    return
            print("❌添加失败")

    def reviseAI(self) -> None:
        print("修改AI助手数据")
        print("请输入ID:")
        try:
            id_value = int(input())
        except Exception:
            print("输入类型错误，请重新输入整数类型")
            return
        for ai in self.ais:
            if ai is not None and id_value == ai.getId():
                print("可修改属性列表为：name,type,version,online,score")
                print("请输入要要修改的属性和值，用空格分割:")
                try:
                    parts = input().split()
                    attribute = parts[0]
                    value = parts[1]
                except Exception:
                    print("输入有误")
                    return
                if attribute == "name":
                    ai.setName(value)
                elif attribute == "type":
                    if ai.containsChineseIgnoreCase(value, ai.aarry):
                        ai.setType(value)
                    else:
                        print("请输入正确的类型，数据分析助手,图片生成助手,文本生成助手,翻译助手，语音助手")
                        return
                elif attribute == "version":
                    ai.setVer(value)
                elif attribute == "online":
                    try:
                        online = int(value)
                    except Exception:
                        print("值输入错误，请重新输入，(1-是, 0-否)")
                        return
                    if online in (0, 1):
                        ai.setState(online)
                    else:
                        print("值输入错误，请重新输入，(1-是, 0-否)")
                        return
                elif attribute == "score":
                    try:
                        score = float(value)
                    except Exception:
                        print("请输入正确的数字(0-100)")
                        return
                    if score < 0 or score > 100:
                        print("请输入正确的数字(0-100)")
                        return
                    ai.setScore(score)
                else:
                    print("请输入正确输入可修改属性列表内的属性")
                    return
                print(f"✅ 助手【{ai.getId()}】修改成功！")
                return
        print("未找到该ID的助手，请确认是否录入")

    def removeAI(self) -> None:
        print("请输入要删除的AI助手ID:")
        try:
            id_value = int(input())
        except Exception:
            print("输入类型错误，请重新输入整数类型")
            return
        for i in range(len(self.ais)):
            ai = self.ais[i]
            if ai is not None and id_value == ai.getId():
                print(f"✅ 助手【{ai.getName()}】已删除。")
                self.ais[i] = None
                return
        print("未找到该ID的助手，请确认是否录入")

    def startAI(self) -> None:
        print("请输入ID:")
        try:
            id_value = int(input())
        except Exception:
            print("输入类型错误，请重新输入整数类型")
            return
        for ai in self.ais:
            if ai is not None and id_value == ai.getId():
                ai.setState(1)
                print(f"🟢助手【{ai.getName()}】已在运行。")
                return
        print("未找到该ID的助手，请确认是否录入")

    def stopAI(self) -> None:
        print("请输入ID:")
        try:
            id_value = int(input())
        except Exception:
            print("输入类型错误，请重新输入整数类型")
            return
        for ai in self.ais:
            if ai is not None and id_value == ai.getId():
                ai.setState(0)
                print(f"🔴助手【{ai.getName()}】已停止。")
                return
        print("未找到该ID的助手，请确认是否录入")

    def taskAI(self) -> None:
        print("请输入目标AI助手ID:")
        try:
            id_value = int(input())
        except Exception:
            print("输入类型错误，请重新输入整数类型")
            return
        for ai in self.ais:
            if ai is not None and id_value == ai.getId():
                if ai.getState() == 0:
                    print(f"❌{ai.getName()}当前离线，无法执行任务。")
                    return
                print("请输入任务内容:")
                task_value = input().strip()
                ai.setTask(task_value)

                if ai.getType() == "数据分析助手":
                    inst = DataAnalysisAssistant()
                    inst.setImage("📃")
                    inst.setName(ai.getName())
                    inst.setType(ai.getType())
                    inst.setTask(ai.getTask())
                    inst.setValue("数据分析")
                    inst.tasking()
                    inst.type = ai.getType()
                    inst.name = ai.getName()
                    inst.analysis()
                    return
                if ai.getType() == "图片生成助手":
                    inst = ImageGenerationAssistant()
                    inst.setImage("🎞️")
                    inst.setName(ai.getName())
                    inst.setType(ai.getType())
                    inst.setTask(ai.getTask())
                    inst.setValue("图片生成")
                    inst.tasking()
                    inst.type = ai.getType()
                    inst.name = ai.getName()
                    inst.painting()
                    return
                if ai.getType() == "文本生成助手":
                    inst = TextGenerationAssistant()
                    inst.setImage("🖹")
                    inst.setName(ai.getName())
                    inst.setType(ai.getType())
                    inst.setTask(ai.getTask())
                    inst.setValue("文本生成")
                    inst.tasking()
                    inst.type = ai.getType()
                    inst.name = ai.getName()
                    inst.writing()
                    return
                if ai.getType() == "翻译助手":
                    inst = TranslationAssistant()
                    inst.setImage("🧑‍🏫")
                    inst.setName(ai.getName())
                    inst.setType(ai.getType())
                    inst.setTask(ai.getTask())
                    inst.setValue("翻译")
                    inst.tasking()
                    inst.type = ai.getType()
                    inst.name = ai.getName()
                    inst.translation()
                    return
                if ai.getType() == "语音助手":
                    inst = VoiceAssistant()
                    inst.setImage("🧑‍🏫")
                    inst.setName(ai.getName())
                    inst.setType(ai.getType())
                    inst.setTask(ai.getTask())
                    inst.setValue("语音")
                    inst.tasking()
                    inst.type = ai.getType()
                    inst.name = ai.getName()
                    inst.talking()
                    return
        print("未找到该ID的助手，请确认是否录入")

    def statisticsAI(self) -> None:
        print("系统统计信息：")
        total = sum(1 for ai in self.ais if ai is not None)
        print(f"总助手数:{total}")
        online = sum(1 for ai in self.ais if ai is not None and ai.getState() == 1)
        print(f"在线助手数:{online}")
        offline = sum(1 for ai in self.ais if ai is not None and ai.getState() == 0)
        print(f"离线助手数:{offline}")
        scores = [ai.getScore() for ai in self.ais if ai is not None]
        average = (sum(scores) / len(scores)) if scores else 0
        print(f"平均能力评分:{average}")


